package com.mxm.mirai.quartz;

import com.mxm.mirai.config.MXM_config;
import com.mxm.mirai.dao.Botbilibili;
import com.mxm.mirai.service.BilibiliService;
import com.mxm.mirai.service.BotgroupsService;
import net.mamoe.mirai.Bot;
import net.mamoe.mirai.contact.Group;
import net.mamoe.mirai.message.data.MessageUtils;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

//@Component
public class Quartz_BiliBili_Run extends QuartzJobBean {
    @Autowired
    BilibiliService bilibiliService;
    @Autowired
    BotgroupsService botgroupsService;
    private static  Botbilibili bili = null;

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        SimpleDateFormat df2 = new SimpleDateFormat("HH:mm:ss");//设置日期格式
//        System.out.println(context.getJobDetail().getJobDataMap().getString("qq"));
        MXM_config.log.BotLog(null,"===================BiliBili任务运行中==================="+df2.format(new Date()),true);
        try {
            bili = bilibiliService.getbilibilivideo();
        }catch (NullPointerException e){
            bili = null;
        }
        if (null != bili) {
            for (Bot bot : Bot.getBotInstances()) {
                for (Group group:bot.getGroups()){
                    if("1".equals(botgroupsService.QueryBotGroupsState(String.valueOf(bot.getId()),String.valueOf(group.getId()),"bilibilMonitor"))){
                        QQ_group_sendMessage(bot,group,bili);
                    }
                }
            }
        }
    }
    /**
     * 获取
     * @param bot
     * @param group
     */
    public void QQ_group_sendMessage(Bot bot, Group group, Botbilibili bili){
        try {
            if (bot.isOnline()) {//在线则发送
                final String imageid = group.uploadImage(new URL(bili.getImg())).getImageId();
                group.sendMessage(
                        MessageUtils.newImage(imageid) // 演示图片, 可能已过期
                                .plus("\n标题:" + bili.getTitle())
                                .plus("\n集数:" + bili.getPub_index())
                                .plus("\n更新时间:" + bili.getPub_time())
                                .plus("\n地址:" + bili.getUrl())
                );
            }
        } catch (MalformedURLException e) {
            MXM_config.log.BotLog(String.valueOf(bot.getId()),"哔哩哔哩监控任务发送出错了",true);
        }
    }

}
